<template>
  <section>
    <van-sticky>
      <PageHeader title="择偶要求" />
    </van-sticky>

    <template v-if="member">
      <van-cell title="年龄"
                :value="(member.expect_age_from > 0 ? member.expect_age_from + '岁-' : '不限-') + (member.expect_age_to > 0 ? member.expect_age_to + '岁' : '不限')"
                is-link
                @click="agePopupVisible=true" />
      <van-cell title="身高"
                :value="(member.expect_height_from > 0 ? member.expect_height_from + 'CM-' : '不限-') + (member.expect_height_to > 0 ? member.expect_height_to + 'CM' : '不限')"
                is-link
                @click="heightPopupVisible=true" />
      <van-cell title="体重"
                :value="(member.expect_weight_from > 0 ? member.expect_weight_from + 'KG-' : '不限-') + (member.expect_weight_to > 0 ? member.expect_weight_to + 'KG' : '不限')"
                is-link
                @click="weightPopupVisible=true" />
      <van-cell title="婚姻状况"
                :value="member.expect_marriage_status_str_label"
                is-link
                @click="marriageStatusPopupVisible=true" />
      <van-cell title="学历"
                :value="member.expect_education_type_str"
                is-link
                @click="educationTypesSheetVisible=true" />
      <van-cell title="收入"
                :value="member.expect_income_type_str"
                is-link
                @click="expectIncomesSheetVisible=true" />
      <van-cell title="房产"
                :value="member.expect_house_status > 0 ? member.expect_house_status_str + '('+member.expect_house_location_str+')' : ''"
                is-link
                @click="$router.push({name: 'MyProfileExpectHouseStatus'})" />
      <van-cell title="购车"
                :value="member.expect_car_status_str"
                is-link
                @click="carStatusSheetVisible=true" />
      <van-cell title="小孩情况"
                :value="member.expect_kids_status_str"
                is-link
                @click="kidsSheetVisible=true" />
      <van-cell title="诚信认证"
                :value="member.expect_verify_status_str"
                is-link
                @click="verifyStatusVisible=true" />
      <van-cell title="所在地区"
                :value="member.expect_location_str"
                is-link
                @click="onShowRegionPopup('live')" />

      <van-popup v-model="agePopupVisible" position="bottom">
        <van-picker show-toolbar title="年龄" :columns="ageColumns" @confirm="onAgePopupConfirm" @cancel="onAgePopupCancel" />
      </van-popup>

      <van-popup v-model="heightPopupVisible" position="bottom">
        <van-picker show-toolbar title="身高" :columns="heightColumns" @confirm="onHeightPopupConfirm" @cancel="onHeightPopupCancel" />
      </van-popup>

      <van-popup v-model="weightPopupVisible" position="bottom">
        <van-picker show-toolbar title="体重" :columns="weightColumns" @confirm="onWeightPopupConfirm" @cancel="onWeightPopupCancel" />
      </van-popup>

      <van-popup v-model="marriageStatusPopupVisible" position="bottom">
        <div class="text-center font-big strong pt20">
          婚姻状况
        </div>
        <div class="text-center pd20 font-common">
          <van-checkbox-group v-model="formData.expect_marriage_status" direction="horizontal">
            <van-checkbox :name="item.value" shape="square" v-for="(item, index) in marriageStatusActions" :key="index">{{item.name}}</van-checkbox>
          </van-checkbox-group>
        </div>

        <div class="text-center pb20 pl20 pr20">
          <van-button round block type="primary" @click="onExpectMarriageStatusConfirm">确定</van-button>
        </div>
      </van-popup>

      <van-action-sheet
        v-model="educationTypesSheetVisible"
        :actions="educationTypesActions"
        cancel-text="取消"
        description="最低学历要求"
        close-on-click-action
        @select="onEducationTypesActionsSelect"
      />

      <van-action-sheet
        v-model="expectIncomesSheetVisible"
        :actions="incomesActions"
        cancel-text="取消"
        description="最低收入要求"
        close-on-click-action
        @select="onExpectIncomesActionsSelect"
      />

      <van-action-sheet
        v-model="kidsSheetVisible"
        :actions="kidsActions"
        cancel-text="取消"
        description="孩子情况"
        close-on-click-action
        @select="onKidsActionsSelect"
      />

      <van-action-sheet
        v-model="carStatusSheetVisible"
        :actions="carStatusActions"
        cancel-text="取消"
        description="购车情况"
        close-on-click-action
        @select="onCarStatusActionsSelect"
      />

      <van-action-sheet
        v-model="verifyStatusVisible"
        :actions="verifyStatusActions"
        cancel-text="取消"
        description="诚信认证"
        close-on-click-action
        @select="onVerifyStatusActionsSelect"
      />

      <van-popup v-model="showRegionPopup" round position="bottom">
        <van-cascader
          v-model="selectedRegions"
          title="请选择所在地区"
          :options="provinceList"
          @close="showRegionPopup = false"
          @change="onRegionCascaderChange"
          @finish="onRegionCascaderFinish"
        />
      </van-popup>
    </template>

  </section>
</template>

<script>
  import {
    memberConstantsUri,
    memberSaveExpectInfoUri, regionChildrenUri
  } from "../../../common/api";
  import PageHeader from "../../componets/PageHeader";
  import Vue from 'vue';
  import {Sticky, Field, Button, Toast, Picker, Popup, Checkbox, CheckboxGroup} from 'vant';
  Vue.use(Sticky).use(Field).use(Button).use(Toast).use(Picker).use(Popup).use(Checkbox).use(CheckboxGroup);

  let ages = [];
  ages.push(0);
  for (let i = 20; i <= 70; i++) {
    ages.push(i);
  }

  let heights = [];
  heights.push(0);
  for (let i = 145; i <= 220; i++) {
    heights.push(i);
  }

  let weights = [];
  weights.push(0);
  for (let i = 35; i <= 110; i++) {
    weights.push(i);
  }

  export default {
    components: {
      PageHeader
    },
    data() {
      return {
        member: null,
        user: null,

        showRegionPopup: false,
        selectedRegions: '',
        provinceList: [],
        cityList: [],
        regionPopupType: '',

        marriageStatusActions: [],

        agePopupVisible: false,
        ageColumns: [],
        heightPopupVisible: false,
        heightColumns: [],
        weightPopupVisible: false,
        weightColumns: [],
        marriageStatusPopupVisible: false,
        educationTypesSheetVisible: false,
        educationTypesActions: [],
        expectIncomesSheetVisible: false,
        incomesActions: [],
        carStatusSheetVisible: false,
        carStatusActions: [],
        kidsSheetVisible: false,
        kidsActions: [],
        childTypesVisible: false,
        childTypesActions: [],
        verifyStatusVisible: false,
        verifyStatusActions: [
          {
            name: '不限',
            value: 0
          },
          {
            name: '已认证',
            value: 1
          }
        ],

        formData: {
          expect_marriage_status: []
        }
      }
    },
    methods: {
      onAgePopupCancel() {
        this.agePopupVisible = false;
      },
      onAgePopupConfirm(value, index) {
        this.member.expect_age_from = ages[index[0]];
        this.member.expect_age_to = ages[index[1]];
        this.agePopupVisible = false;
        this.saveMemberProfile();
      },
      onHeightPopupCancel() {
        this.heightPopupVisible = false;
      },
      onHeightPopupConfirm(value, index) {
        this.member.expect_height_from = heights[index[0]];
        this.member.expect_height_to = heights[index[1]];
        this.heightPopupVisible = false;
        this.saveMemberProfile();
      },
      onWeightPopupCancel() {
        this.weightPopupVisible = false;
      },
      onWeightPopupConfirm(value, index) {
        this.member.expect_weight_from = weights[index[0]];
        this.member.expect_weight_to = weights[index[1]];
        this.weightPopupVisible = false;
        this.saveMemberProfile();
      },
      onExpectMarriageStatusConfirm() {
        this.marriageStatusPopupVisible = false;
        this.saveMemberProfile();
      },
      onEducationTypesActionsSelect(item) {
        this.educationTypesSheetVisible = false;
        this.member.expect_education_type = item.value;
        this.saveMemberProfile();
      },
      onExpectIncomesActionsSelect(item) {
        this.expectIncomesSheetVisible = false;
        this.member.expect_income_type = item.value;
        this.saveMemberProfile();
      },
      onCarStatusActionsSelect(item) {
        this.carStatusSheetVisible = false;
        this.member.expect_car_status = item.value;
        this.saveMemberProfile();
      },
      onKidsActionsSelect(item) {
        this.kidsSheetVisible = false;
        this.member.expect_kids_status = item.value;
        this.saveMemberProfile();
      },
      onVerifyStatusActionsSelect(item) {
        this.verifyStatusVisible = false;
        this.member.expect_verify_status = item.value;
        this.saveMemberProfile();
      },
      getRegions(parentId, callback) {
        const that = this;
        const url = regionChildrenUri + '?parent_id=' + parentId;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            Toast.fail(msg);
          } else {
            callback(data.regions);
          }
        }, response => {
          // error callback
        })
      },
      onRegionCascaderChange(option) {
        const tabIndex = option.tabIndex;
        const value = option.value;
        if(tabIndex == 0) {
          if(value > 0) {
            const provinceList = this.provinceList;
            let provinceIndex = 0;
            for (let i = 0; i < provinceList.length; i++) {
              if(value == provinceList[i].value) {
                provinceIndex = i;
                break;
              }
            }
            this.getRegions(value, (regions) => {
              let children = [];
              children.push({
                text: '不限',
                value: 0
              });
              for (let i = 0; i < regions.length; i++) {
                children.push({
                  text: regions[i].region_name,
                  value: regions[i].region_id
                })
              }
              let province = provinceList[provinceIndex];
              province.children = children;
              this.$set(provinceList, provinceIndex, province);
            })
          } else {
            let children = [];
            children.push({
              text: '不限',
              value: 0
            });
            const provinceList = this.provinceList;
            let provinceIndex = 0;
            let province = provinceList[provinceIndex];
            province.children = children;
            this.$set(provinceList, provinceIndex, province);
          }
        }
      },
      onRegionCascaderFinish({ selectedOptions }) {
        if(this.regionPopupType == 'live') {
          this.member.expect_location = selectedOptions[1].value;
        }
        this.showRegionPopup = false;
        this.saveMemberProfile();
      },
      onShowRegionPopup(type) {
        this.regionPopupType = type;
        this.showRegionPopup = true;
      },
      getConstants() {
        const that = this;
        const url = memberConstantsUri;
        this.$http.get(url).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            Toast.fail(msg);
          } else {
            let genderActions = [];
            for (let key in data.genders) {
              genderActions.push({
                name: data.genders[key],
                value: key
              })
            }
            that.genderActions = genderActions;

            let marriageStatusActions = [];
            for (let key in data.marriage_status) {
              marriageStatusActions.push({
                name: data.marriage_status[key],
                value: key
              })
            }
            that.marriageStatusActions = marriageStatusActions;

            let heightActions = [];
            for (let i = 130; i < 220; i++) {
              heightActions.push({
                name: i + 'CM',
                value: i
              })
            }
            that.heightActions = heightActions;

            let weightActions = [];
            for (let i = 35; i < 120; i++) {
              weightActions.push({
                name: i + 'KG',
                value: i
              })
            }
            that.weightActions = weightActions;

            let educationTypesActions = [];
            for (let key in data.education_types) {
              educationTypesActions.push({
                name: data.education_types[key],
                value: key
              })
            }
            that.educationTypesActions = educationTypesActions;

            let jobsActions = [];
            for (let key in data.jobs) {
              jobsActions.push({
                name: data.jobs[key],
                value: key
              })
            }
            that.jobsActions = jobsActions;

            let incomesActions = [];
            for (let key in data.incomes) {
              incomesActions.push({
                name: data.incomes[key],
                value: key
              })
            }
            that.incomesActions = incomesActions;

            let carStatusActions = [];
            for (let key in data.car_status) {
              carStatusActions.push({
                name: data.car_status[key],
                value: key
              })
            }
            that.carStatusActions = carStatusActions;

            let kidsActions = [];
            for (let key in data.kids) {
              kidsActions.push({
                name: data.kids[key],
                value: key
              })
            }
            that.kidsActions = kidsActions;

            let bloodTypesActions = [];
            for (let key in data.blood_types) {
              bloodTypesActions.push({
                name: data.blood_types[key],
                value: key
              })
            }
            that.bloodTypesActions = bloodTypesActions;

            let nationsActions = [];
            for (let key in data.nations) {
              nationsActions.push({
                name: data.nations[key],
                value: key
              })
            }
            that.nationsActions = nationsActions;

            let faithsActions = [];
            for (let key in data.faiths) {
              faithsActions.push({
                name: data.faiths[key],
                value: key
              })
            }
            that.faithsActions = faithsActions;

            let smokesActions = [];
            for (let key in data.smokes) {
              smokesActions.push({
                name: data.smokes[key],
                value: key
              })
            }
            that.smokesActions = smokesActions;

            let drinksActions = [];
            for (let key in data.drinks) {
              drinksActions.push({
                name: data.drinks[key],
                value: key
              })
            }
            that.drinksActions = drinksActions;

            let jobTypesActions = [];
            for (let key in data.job_types) {
              jobTypesActions.push({
                name: data.job_types[key],
                value: key
              })
            }
            that.jobTypesActions = jobTypesActions;

            let distanceRelationshipTypesActions = [];
            for (let key in data.distance_relationship_types) {
              distanceRelationshipTypesActions.push({
                name: data.distance_relationship_types[key],
                value: key
              })
            }
            that.distanceRelationshipTypesActions = distanceRelationshipTypesActions;

            let childTypesActions = [];
            for (let key in data.child_types) {
              childTypesActions.push({
                name: data.child_types[key],
                value: key
              })
            }
            that.childTypesActions = childTypesActions;

            let liveParentsTypesActions = [];
            for (let key in data.live_parents_types) {
              liveParentsTypesActions.push({
                name: data.live_parents_types[key],
                value: key
              })
            }
            that.liveParentsTypesActions = liveParentsTypesActions;
          }
        }, response => {
          // error callback
        })
      },
      saveMemberProfile() {
        const that = this;
        this.member.expect_marriage_status = this.formData.expect_marriage_status.join(',');
        that.$http.post(memberSaveExpectInfoUri, this.member, {emulateJSON: true}).then(response => {
          let {msg, code, data} = response.body
          if (code != 0) {
            Toast.fail(msg)
          } else {
            that.member = data.member;
            that.GLOBAL.memberProfile = data.member;
            if(that.member) {
              that.member.expect_marriage_status_str_label = that.member.expect_marriage_status_str.join(' ');
            }
            Toast.success('保存成功');
          }
        }, response => {
          Toast.fail('发生错误')
        })
      }
    },
    mounted: function () {
      this.member = this.GLOBAL.memberProfile;
      this.user = this.GLOBAL.userInfo;
      if(this.member) {
        this.member.expect_marriage_status_str_label = this.member.expect_marriage_status_str.join(' ');
      }

      this.EventBus.$on('OnUserLogined', () => {
        this.user = this.GLOBAL.userInfo;
        this.member = this.GLOBAL.memberProfile;
        if(this.member) {
          this.member.expect_marriage_status_str_label = this.member.expect_marriage_status_str.join(' ');
        }
      });

      let ageValuess = [];
      ageValuess.push('不限');
      for (let i = 1; i < ages.length; i++) {
        ageValuess.push(ages[i] + '岁');
      }
      this.ageColumns = [
        {values: ageValuess, defaultIndex: 0},
        {values: ageValuess, defaultIndex: 0}
      ];

      let heightValuess = [];
      heightValuess.push('不限');
      for (let i = 1; i < heights.length; i++) {
        heightValuess.push(heights[i] + 'CM');
      }
      this.heightColumns = [
        {values: heightValuess, defaultIndex: 0},
        {values: heightValuess, defaultIndex: 0}
      ];

      let weightValues = [];
      weightValues.push('不限');
      for (let i = 1; i < weights.length; i++) {
        weightValues.push(weights[i] + 'KG');
      }
      this.weightColumns = [
        {values: weightValues, defaultIndex: 0},
        {values: weightValues, defaultIndex: 0}
      ];

      this.getConstants();
      this.getRegions(1, (regions) => {
        let provinceList = [];
        provinceList.push({
          text: '不限',
          value: 0,
          children: []
        });
        for (let i = 0; i < regions.length; i++) {
          provinceList.push({
            text: regions[i].region_name,
            value: regions[i].region_id,
            children: []
          })
        }
        this.provinceList = provinceList;
      });
    }
  }
</script>

<style scoped>

</style>
